import subprocess
import sys
from influxdb_client import InfluxDBClient
import json
from influxdb_client.client.write_api import SYNCHRONOUS

influxdb_token=''
influxdb_host=''
influxdb_org=''
with open('private.json','r',encoding='utf8') as f:
	d=json.load(f)
	influxdb_token=d['influxdb_token']
	influxdb_org=d['influxdb_org']
	influxdb_host=d['influxdb_host']

def extract_mysql_sql_s_insertion_operations():
	with open('mysql.sql','r',encoding='utf8') as f:
		contents=f.read()
	tables={'acoustic_models':'','bt_devices':'','bt_hosts':'','data_preprocessors':'','data_subsets':'','datasets':'','decoders':'','device_descriptions':'','file_dire':'','fpfes':'','language_models':'','lexicon_dicts':'','models':'','post_processors':'','test_projects':'','users':'','bt_tasks':'','tp_to_ucs':'','bt_executions':'','comp_result':''}
	for line in contents.strip().split('\n'):
		if line.startswith('INSERT'):
			tables[line.split()[2][1:-1]]=line
	with open('mysql.sql','w',encoding='utf8') as f:
		for table in tables:
			if tables[table]!='':
				f.write(f'LOCK TABLES `{table}` WRITE;\n{tables[table]}\nUNLOCK TABLES;')

if __name__=='__main__':
	help_str='usage:\n(1) python py_file mysql out\n(2) python py_file influxdb out\n(3) python py_file influxdb in\n'
	if len(sys.argv)<3:
		print(help_str)
		sys.exit(0)
	db=sys.argv[1]
	op=sys.argv[2]
	if db=='mysql' and op=='out':
		subprocess.run('./backup_mysql.sh')
		extract_mysql_sql_s_insertion_operations()
	elif db=='influxdb' and op=='out':
		with InfluxDBClient(url=f'http://{influxdb_host}:8086',token=influxdb_token,org=influxdb_org) as client:
			tables=client.query_api().query('from(bucket:"btresults")|>range(start:0)')
			output=tables.to_json(indent=4)
			with open('influxdb.json','w',encoding='utf8') as f:
				f.write(f'{{"output":{output}}}')
			d={}
			with open('influxdb.json','r',encoding='utf8') as f:
				d=json.load(f)
			new_output=[]
			for o in d['output']:
				new_output.append({'measurement':o['_measurement'],'tags':{'type':o['type']},'time':o['_time'],'fields':{o['_field']:o['_value']}})
			with open('influxdb.json','w',encoding='utf8') as f:
				json.dump({'output':new_output},f,ensure_ascii=False,indent=4)
	elif db=='influxdb' and op=='in':
		with open('influxdb.json','r',encoding='utf8') as f:
			d=json.load(f)
		with InfluxDBClient(url=f'http://{influxdb_host}:8086',token=influxdb_token,org=influxdb_org) as client:
			write_api=client.write_api(write_options=SYNCHRONOUS)
			write_api.write(bucket='btresults',record=d['output'])
	else:
		print(help_str)